package cn.neu.leon.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

/**
 * 该类将情感词典EmotionLexicon.txt文件中的情感词和情感概率以键值对形式放入HashMap中
 * @author kll
 * 
 */
public class EmotionLexicon {
	public HashMap<String, double[]> emotionMap = new HashMap<String, double[]>(); // 存放情感词典的hashmap
	private double prob[] = new double[7]; // 存放情感词典7个情感概率
	private String encoding = "UTF-8"; // 情感词典txt文件的编码格式
	public EmotionLexicon() {
		try {
			
//			String classPath = this.getClass().getClassLoader().getResource("").toString();
////			 System.out.println(Thread.currentThread().getContextClassLoader().getResource("/")); 
////		        System.out.println(this.getClass().getClassLoader().getResource("")); 
////		        System.out.println(ClassLoader.getSystemResource("")); 
////		        System.out.println(this.getClass().getResource("")); 
////		        System.out.println(this.getClass().getResource(""));//Class文件所在路径 
////		        System.out.println(System.getProperty("user.dir")); 
//			
//			System.out.println(classPath+"		"+classPath.substring(0, classPath.length()-8));
			File file = new File("./library/EmotionLexicon_v2.txt"); // 情感词典
			if (file.isFile() && file.exists()) {
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(file), encoding);
				BufferedReader br = new BufferedReader(read);
				String line = null; //从情感词典txt文件中读取的每一行
				String[] str = null;//将一行分割后各部分放入字符串数组中
				/*按行读取，直至文件末尾*/
				while ((line = br.readLine()) != null) { 
					str = line.split("="); // 以“=”为标志分割一行，str[0]存为key，str[1]分割后存为double数组
					
                 /*分割情感概率str[1]，放入prob数组中*/
					for (int i = 0; i < 7; i++) {
						prob[i] = Double.parseDouble(str[1].split(" ")[i]); 
					}
					mapadd(str[0], prob); 

				}
				read.close();
			} else {
				System.out.println("情感词典载入失败！");
			}
		} catch (Exception e) {
			System.out.println("情感词典读取失败！");
			e.printStackTrace();
		}
	}

	public HashMap<String, double[]> getEmotionMap() {
		return emotionMap;
	}

	public void setEmotionMap(HashMap<String, double[]> emotionMap) {
		this.emotionMap = emotionMap;
	}

	/**
	 * 向map中添加键值对，用自定义的方法是为了，每次调用都会建立临时内存，才能使map中每个key对应不同的value
	 * @param str
	 * @param prob
	 */
	public void mapadd(String str, double prob[]) {
		String str1 = str;
		double prob1[] = new double[7];
		for (int i = 0; i < 7; i++) {
			prob1[i] = prob[i];
		}
		emotionMap.put(str1, prob1);
	}
}


